package com.song.tradition.page.components

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.*
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.rememberPagerState

import com.song.tradition.entity.StoryData
import com.song.tradition.R
import com.song.tradition.ui.theme.customCardBgColor
import kotlinx.coroutines.delay


@OptIn(ExperimentalPagerApi::class)
@Composable
fun Swiper(
    items: Array<StoryData>,
    modifier: Modifier = Modifier,
    timeMillis: Long = 3000L,

) {

    Surface(
        modifier = modifier.fillMaxWidth(),
        shadowElevation = 2.dp,
        shape = RoundedCornerShape(10.dp)
    ) {
        val pagerState = rememberPagerState(initialPage = 0)
        //监听动画执行
        var executeChangePage by remember {
            mutableStateOf(false)
        }

        var currentPageIndex = 0

        LaunchedEffect(pagerState.currentPage, executeChangePage) {
            if (pagerState.pageCount > 0) {
                delay(timeMillis)
                pagerState.animateScrollToPage((pagerState.currentPage + 1) % (pagerState.pageCount))
            }
        }

        HorizontalPager(count = items.size,
            state = pagerState,
            modifier = Modifier
                .pointerInput(pagerState.currentPage) {
                    awaitPointerEventScope {
                        while (true) {
                            //PointerEventPass.Initial - 本控件优先处理手势，处理后再交给子组件
                            val event = awaitPointerEvent(PointerEventPass.Initial)
                            //获取到第一根按下的手指
                            val dragEvent = event.changes.firstOrNull()
                            when {
                                //当前移动手势是否已被消费
                                dragEvent!!.positionChangeConsumed() -> {
                                    return@awaitPointerEventScope
                                }
                                //是否已经按下(忽略按下手势已消费标记)
                                dragEvent.changedToDownIgnoreConsumed() -> {
                                    //记录下当前的页面索引值
                                    currentPageIndex = pagerState.currentPage
                                }
                                //是否已经抬起(忽略按下手势已消费标记)
                                dragEvent.changedToUpIgnoreConsumed() -> {
                                    //当页面没有任何滚动/动画的时候pagerState.targetPage为null，这个时候是单击事件
                                    //当pageCount大于1，且手指抬起时如果页面没有改变，就手动触发动画
                                    if (currentPageIndex == pagerState.currentPage && pagerState.pageCount > 1) {
                                        executeChangePage = !executeChangePage
                                    }
                                }
                            }
                        }
                    }
                }
                .fillMaxWidth()
        ) { index ->
            SwiperItem(items[index])
        }


    }

}

@Composable
fun SwiperItem(data: StoryData) {
    Column(modifier = Modifier.fillMaxWidth().background(customCardBgColor)) {

        Image(
            painterResource(id = data.resId),
            contentDescription = data.name,
            modifier = Modifier.fillMaxWidth(),
            contentScale = ContentScale.FillWidth
        )

        Spacer(modifier = Modifier.height(16.dp))
        Text(text = data.description, lineHeight = 20.sp, modifier = Modifier.fillMaxWidth().height(80.dp).padding(horizontal = 8.dp))

    }

}

@Preview(showBackground = true)
@Composable
fun SwiperItemText() {
    val data = StoryData(
        R.drawable.wang, "望", "观察病人神、色、形、态的变化。" +
                "“神”是精神、神气状态；" +
                "“色”是五脏气血的外在荣枯色泽的表现；" +
                "“形”是形体丰实虚弱的徵象；" +
                "“态”是动态的灵活呆滞的表现。"
    )

    SwiperItem(data = data)
}